﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Messaging;

namespace Remoting.Reactive.Windowing
{
    internal sealed class LocalMessageReceiverObservable : ILocalMessageReceiverObservable
    {
        private readonly LocalMessageReceiver _localMessageReceiver;

        public LocalMessageReceiverObservable(LocalMessageReceiver localMessageReceiver)
        {
            Guard.Requires<ArgumentNullException>(localMessageReceiver != null);
            _localMessageReceiver = localMessageReceiver;
        }

        public void Dispose()
        {
            _localMessageReceiver.Dispose();
        }

        public void Listen()
        {
            _localMessageReceiver.Listen();
        }

        public IObservable<IMessageReceived> Receive()
        {
            return Observable.FromEvent<MessageReceivedEventArgs>(
                eh => _localMessageReceiver.MessageReceived += eh,
                eh => _localMessageReceiver.MessageReceived -= eh)
                .Select(evt => new MessageReceived(evt.EventArgs) as IMessageReceived)
                .Publish()
                .RefCount();
        }

        public IEnumerable<string> AllowedSenderDomains
        {
            get { return _localMessageReceiver.AllowedSenderDomains;}
        }

        public bool DisableSenderTrustCheck
        {
            get { return _localMessageReceiver.DisableSenderTrustCheck; }
            set { _localMessageReceiver.DisableSenderTrustCheck = value; }
        }
            
        public ReceiverNameScope NameScope
        {
            get { return _localMessageReceiver.NameScope; }
        }
        
        public string ReceiverName
        {
            get { return _localMessageReceiver.ReceiverName; }
        }
    }
}
